/*
 * Copyright (c) 2009 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package com.sun.spot.wot.gateway;

import java.io.IOException;
import javax.microedition.io.Connector;
import com.sun.spot.ipv6.io.j2me.udp.UDPConnection;
import com.sun.spot.ipv6.io.j2me.udp.UDPDatagram;
import java.util.Date;

/**
 *
 * @author vgupta
 */
class UDP6Forwarder implements DeviceForwarder {
    private UDPConnection conn = null;

    public void openConn(String addr) {
        try {
//            System.out.println("UDPForwarder opening connection to addr: " + addr);
            conn = (UDPConnection) Connector.open("udp://" + addr);
            conn.setTimeout(15000);
        } catch (IOException ex) {
            ex.printStackTrace();
            conn = null;
            System.err.println("Failed to open datagram connection to " + addr);
        } finally {

        }
    }

    public void closeConn() {
        try {
            if (conn != null) conn.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public int sendAndGetResponse(String addr, byte[] sndBuf, int off1, int len1, byte[] rcvBuf, int off2) throws IOException {
        Date d = new Date();
        openConn(addr);
        UDPDatagram dg = (UDPDatagram) conn.newDatagram(conn.getMaximumLength());
        UDPDatagram idg = (UDPDatagram) conn.newDatagram(conn.getMaximumLength());

        // First send the data
        dg.write(sndBuf, off1, len1);
        d.setTime(System.currentTimeMillis());
//        System.out.println(d.toString() + ", Sending data in UDP6Forwarder to " +
//                addr);
//                new Inet6Address(idg.getDstAddresss()).toString() + ", port " + dg.getDstPort());
        conn.send(dg);
//        System.out.println("Sent data [len=" + len1 + "]:\n" +
//                PrettyPrint.prettyPrint(sndBuf, off1, len1));
        d.setTime(System.currentTimeMillis());
//        System.out.println(d.toString() + ", Awaiting response in UDP6Forwarder");
        conn.receive(idg);
        d.setTime(System.currentTimeMillis());
//        System.out.println(d.toString() + ", Received data in UDP6Forwarder from " +
//                new Inet6Address(idg.getSrcAddress()).toString() + ", port " + idg.getSrcPort());
        byte[] data = idg.getData();
        System.arraycopy(data, 0, rcvBuf, off2, data.length);
//        System.out.println("Reading data, off=" + off2);
//        System.out.println("Received data [len=" + data.length + "]:\n" +
//                    PrettyPrint.prettyPrint(rcvBuf, off2, data.length));

        //closeConn();
        return data.length;
    }

    public void close() {
        closeConn();
    }
}
